package outlookBar;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.Icon;
import javax.swing.JComponent;

/**
 * This is a bar section which has the header and the main component
 * @see #OutlookBar
 * @author Carlos E. Descalzi
 */
public class BarSection extends JComponent{
	
	private BarHeader header;
	private JComponent component = null;

	private ActionListener listener = new ActionListener(){
		public void actionPerformed(ActionEvent event){
			fireActionPerformed();
		}
	};
	
	private ArrayList<ActionListener> listeners = new ArrayList<ActionListener>();
	
	public BarSection(BarHeader header,JComponent component){
		setLayout(new BorderLayout());
		setHeader(header);
		setComponent(component);
	}

	public BarSection(String text,Icon icon,JComponent component){
		this(new DefaultBarHeader(text,icon),component);
	}
	
	public synchronized void addActionListener(ActionListener listener){
		if (!listeners.contains(listener)){
			ArrayList<ActionListener> newListeners = new ArrayList<ActionListener>(listeners);
			newListeners.add(listener);
			listeners = newListeners;
		}
	}

	public synchronized void removeActionListener(ActionListener listener){
		if (listeners.contains(listener)){
			ArrayList<ActionListener> newListeners = new ArrayList<ActionListener>(listeners);
			newListeners.add(listener);
			listeners = newListeners;
		}
	}
	
	private void fireActionPerformed(){
		
		ActionEvent event = new ActionEvent(this,ActionEvent.ACTION_PERFORMED,"action");
		
		for (ActionListener listener:listeners){
			listener.actionPerformed(event);
		}
	}
	
	public JComponent getComponent(){
		return this.component;
	}
	
	public void setComponent(JComponent component){
		if (this.component != null){
			this.remove(this.component);
		}
		
		this.component = component;
		
		if (this.component != null){
			this.component.setVisible(false);
			this.add(this.component,BorderLayout.CENTER);
		}
		
		validate();
	}
	
	public void setHeader(BarHeader header){
		if (this.header != null){
			this.header.removeActionListener(listener);
			this.remove(header);
		}
		this.header = header;
		
		if (this.header != null){
			this.header.addActionListener(listener);
			this.add(header,BorderLayout.NORTH);
		}
	}
	
	public BarHeader getHeader(){
		return header;
	}
	
	public Dimension getHeaderDimension(){
		return header.getPreferredSize();
	}
	
	public void setComponentVisible(boolean visible){
		if (this.component != null){
			this.component.setVisible(visible);
		}
	}
	
	public boolean isComponentVisible(){
		return this.component != null && 
			this.component.isVisible();
	}
	
}
